package com.pig4cloud.pig.hu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.exception.CheckedException;
import com.pig4cloud.pig.hu.entity.Activity;
import com.pig4cloud.pig.hu.mapper.ActivityMapper;
import com.pig4cloud.pig.hu.service.ActivityService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService{
	/**
	 * 每天 9:40 由 XXL-JOB 触发
	 * 把 start_time <= now 且未上架的活动批量上架
	 */
	public void onShelf() {
		LocalDateTime now = LocalDateTime.now();
		LambdaUpdateWrapper<Activity> uw = Wrappers.<Activity>lambdaUpdate()
				.set(Activity::getStatus, 1)          // 1 = 已上架
				.eq(Activity::getStatus, 2)           // 2 = 待上架
				.le(Activity::getStart, now);     // 已到开始时间
		this.update(uw);
	}
	/*
	活动上下架
	 */
	public boolean toggleStatus(Long activityId) {
		// 1 变 2，2 变 1
		return this.lambdaUpdate()
				.setSql("status = CASE status WHEN 1 THEN 2 WHEN 2 THEN 1 END")
				.eq(Activity::getActivityId, activityId)
				.in(Activity::getStatus, 1, 2)   // 只改 1 或 2 的记录，防止脏数据
				.update();
	}

	public boolean anyExists(LambdaQueryWrapper<Activity> wrapper) {
		return baseMapper.selectCount(wrapper) > 0;
	}
	@Override
	public void checkUnique(Activity activity) {
		if (anyExists(Wrappers.<Activity>lambdaQuery()
				.eq(Activity::getActivityName, activity.getActivityName())
				.ne(activity.getActivityId() != null, Activity::getActivityId, activity.getActivityId()))) {
			throw new CheckedException("活动已存在");
		}
		if (anyExists(Wrappers.<Activity>lambdaQuery()
				.eq(Activity::getTitle, activity.getTitle())
				.ne(activity.getActivityId() != null, Activity::getActivityId, activity.getActivityId()))) {
			throw new CheckedException("标题重复");
		}
	}
}
